package com.lanou.web.controller;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanou.entity.*;


import com.lanou.service.SearchService;

import com.lanou.utils.ShiHuiResult;
import io.swagger.annotations.ApiOperation;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;


import java.io.IOException;
import java.util.Map;


@RestController
public class SearchController {
    @Autowired
    private SearchService searchService;

    @ApiOperation("初始化")
    @GetMapping("/search/initialize")
    public Map<String,Object> findAll() throws IOException, SolrServerException {
        Page<SearchItem> pageObject = PageHelper.startPage(1, 60);
        searchService.findAll();
        for (int i = 2; i <= pageObject.getPages(); i++) {
            PageHelper.startPage(i, 60);
            searchService.findAll();
        }
        return ShiHuiResult.ok();
    }

    @ApiOperation("关键字查询")
    @GetMapping("/search/keyword")
   public Map<String,Object> searchByKeyword(String keyword,
                                             @RequestParam(value="page", defaultValue="1")Integer page,
                                             @RequestParam(value = "rows",defaultValue = "60") Integer rows,
                                             @RequestParam(value = "sort",defaultValue = "1") Integer sort)
                                                throws IOException, SolrServerException {
        SearchItem2 searchItemList = searchService.searchByKeyword(keyword,page,rows,sort);
        if (searchItemList.getRownums() > 0 ){
            return ShiHuiResult.ok(searchItemList);
      }else{
            return ShiHuiResult.error(500,"关键字查询失败");
        }

    }

    @ApiOperation("新增/修改商品")
    @GetMapping("/search/update")
    public Map<String, Object> addItemToSolr(Long id) throws IOException, SolrServerException {
        boolean result = searchService.addItemToSolr(id);
        if (result){
            return ShiHuiResult.ok();
        }else {
            return ShiHuiResult.error(500,"添加失败");
        }


    }
    @ApiOperation("删除商品")
    @GetMapping("/search/delete")
    public Map<String, Object> delItemToSolr(Long id) throws IOException, SolrServerException {
        boolean result = searchService.delItemToSolr(id);
        if (result) {
            return ShiHuiResult.ok();
        } else {
            return ShiHuiResult.error(500, "删除失败");
        }


    }

}
